"use strict";
var vk; // 全局vk实例
// 涉及的表名
const dbName = require("../../../dao/config.js");

var db = uniCloud.database(); // 全局数据库引用
var _ = db.command; // 数据库操作符
var $ = _.aggregate; // 聚合查询操作符
/**
 * 权限注意：访问以下链接查看
 * 文档地址：https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#内置权限
 */
var cloudObject = {
	isCloudObject: true, // 标记为云对象模式
	/**
	 * 请求前处理，主要用于调用方法之前进行预处理，一般用于拦截器、统一的身份验证、参数校验、定义全局对象等。
	 * 文档地址：https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#before-预处理
	 */
	_before: async function() {
		vk = this.vk; // 将vk定义为全局对象
		// let { customUtil, uniID, config, pubFun } = this.getUtil(); // 获取工具包
	},
	/**
	 * 请求后处理，主要用于处理本次调用方法的返回结果或者抛出的错误
	 * 文档地址：https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#after-后处理
	 */
	_after: async function(options) {
		let {
			err,
			res
		} = options;
		if (err) {
			return; // 如果方法抛出错误，直接return;不处理
		}
		return res;
	},

	/**
	 * 获取首页基础数据
	 * @url admin/business/kh.stats.getUserCount 前端调用的url参数地址
	 */
	getBaseInfoCount: async function(data) {
		let res = {
			code: 0,
			msg: "",
		};
		// 业务逻辑开始-----------------------------------------------------------
		let {
			todayStart,
			todayEnd,
			yesterdayStart,
			yesterdayEnd
		} =
		vk.pubfn.getCommonTime();
		let day7Start = vk.pubfn.getOffsetTime(todayStart, {
			day: 7,
			mode: "before", // after 之后 before 之前
		});
		// 并发
		let batchRunRes = await vk.pubfn.batchRun({
			// 主执行函数
			main: [
				// 今日销售额
				async () => {
						return await vk.daoCenter.orderDao.sum({
							fieldName: "amount_info.payment_amount",
							whereJson: {
								status: _.gte(1),
								_add_time: _.gte(todayStart).lte(todayEnd),
							},
						});
					},

					// 昨日销售额
					async () => {
							return await vk.daoCenter.orderDao.sum({
								fieldName: "amount_info.payment_amount",
								whereJson: {
									status: _.gte(1),
									_add_time: _.gte(yesterdayStart).lte(yesterdayEnd),
								},
							});
						},
						async () => {
								return await vk.daoCenter.orderDao.sum({
									fieldName: "amount_info.payment_amount",
									whereJson: {
										status: _.gte(1),
									},
								});
							},
							// 今日新增用户数量
							async () => {
									return await vk.daoCenter.orderDao.count({
										status: _.gte(1),
										_add_time: _.gte(todayStart).lte(todayEnd),
									});
								},
								// 昨日新增用户数量
								async () => {
										return await vk.daoCenter.orderDao.count({
											status: _.gte(1),
											_add_time: _.gte(yesterdayStart).lte(yesterdayEnd),
										});
									},
									// 近总用户数量
									async () => {
											return await vk.daoCenter.orderDao.count({
												status: _.gte(1),
											});
										},
										// 今日新增用户数量
										async () => {
												return await vk.daoCenter.userDao.count({
													register_date: _.gte(todayStart).lte(todayEnd),
												});
											},
											// 昨日新增用户数量
											async () => {
													return await vk.daoCenter.userDao.count({
														register_date: _.gte(yesterdayStart).lte(yesterdayEnd),
													});
												},
												// 近总用户数量
												async () => {
														return await vk.daoCenter.userDao.count({});
													},

													//今日新增客户业务员
													async () => {
															return await vk.baseDao.count({
																dbName: "vk-user-browsing",
																// 主表where条件
																whereJson: {
																	_add_time: _.gte(todayStart).lte(todayEnd),
																},
															});
														},
														//昨日新增客户业务员
														async () => {
																return await vk.baseDao.count({
																	dbName: "vk-user-browsing",
																	// 主表where条件
																	whereJson: {
																		_add_time: _.gte(yesterdayStart).lte(yesterdayEnd),
																	},
																});
															},
															//近总客户业务员
															async () => {
																return  await vk.baseDao.count({
																	dbName: "vk-user-browsing",
																	// 主表where条件
																	whereJson: {},
																});
															},
			],
			// 最大并发量，如果设置为1，则会按顺序执行
			concurrency: 10,
		});
		res.list = batchRunRes.stack;
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},

	//待办事项
	getTodoList: async function(data) {
		let res = {
			code: 0,
			msg: "",
		};
		// 业务逻辑开始-----------------------------------------------------------

		let list = [{
				icon: "el-icon-s-custom",
				color: "rgb(105, 192, 255)",
				title: "用户管理",
				value: 0,
				url: "/pages/user/list",
			},
			{
				icon: "el-icon-user-solid",
				color: "rgb(149, 222, 100)",
				title: "业务员管理",
				value: 0,
				url: "/pages/salesperson_user/list",
			},
			{
				icon: "el-icon-s-goods",
				color: "rgb(255, 156, 110)",
				value: 0,
				title: "商品管理",
				url: "/pages/goods/list",
			},
			{
				icon: "el-icon-s-order",
				value: 0,
				color: "rgb(179, 127, 235)",
				title: "订单管理",
				url: "/pages/order/list?status=1",
			},
			{
				icon: "vk-icon-jiagoufenxiao",
				color: "rgb(92, 219, 211)",
				value: 0,
				title: "返佣管理",
				url: "/pages/salesman/setting",
			},
			{
				icon: "vk-icon-tixianguanli",
				color: "DodgerBlue",
				value: 0,
				title: "提现管理",
				url: "/pages/finance/withdraw/list",
			},

			{
				icon: "el-icon-s-management",
				color: "Violet",
				value: 0,
				title: "优惠券",
				url: "/pages/discount/coupon/list",
			},
			{
				icon: "vk-icon-settings",
				color: "#F56C6C",
				title: "店铺设置",
				value: 0,
				url: "/pages/shop/setting",
			},
		];

		//获取待发货订单
		let orderCount = await vk.daoCenter.orderDao.count({
			status: _.in([1]),
		});

		//获取待开票的订单数
		let invoiceCount = await vk.baseDao.count({
			dbName: "mine-user-invoice-log",
			whereJson: {
				status: _.in([0]),
			},
		});

		list[3].value = orderCount;
		list[6].value = invoiceCount;
		res.list = list;
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},

	/**
	 * 用户统计人数
	 * @url admin/business/kh.stats.getUserCount 前端调用的url参数地址
	 */
	getUserCount: async function(data) {
		let res = {
			code: 0,
			msg: "",
		};
		// 业务逻辑开始-----------------------------------------------------------
		let {
			todayStart,
			todayEnd,
			yesterdayStart,
			yesterdayEnd
		} =
		vk.pubfn.getCommonTime();
		let day7Start = vk.pubfn.getOffsetTime(todayStart, {
			day: 7,
			mode: "before", // after 之后 before 之前
		});
		// 并发
		let batchRunRes = await vk.pubfn.batchRun({
			// 主执行函数
			main: [
				// 总用户数量
				async () => {
						return await vk.daoCenter.userDao.count();
					},
					// 今日新增用户数量
					async () => {
							return await vk.daoCenter.userDao.count({
								register_date: _.gte(todayStart).lte(todayEnd),
							});
						},
						// 昨日新增用户数量
						async () => {
								return await vk.daoCenter.userDao.count({
									register_date: _.gte(yesterdayStart).lte(yesterdayEnd),
								});
							},
							// 近7天新增用户数量
							async () => {
								return await vk.daoCenter.userDao.count({
									register_date: _.gte(day7Start).lte(todayEnd),
								});
							},
			],
			// 最大并发量，如果设置为1，则会按顺序执行
			concurrency: 10,
		});
		res.list = batchRunRes.stack;
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},



	/**
	 * 用户新增统计,按日或月
	 * @url admin/business/kh.stats.getNewUserCountGroup 前端调用的url参数地址
	 */
	getNewUserCountGroup: async function(data) {
		let res = {
			code: 0,
			msg: "",
		};
		// 业务逻辑开始-----------------------------------------------------------
		let {
			mode = "日"
		} = data;
		let group = "新增数";
		let timeFormat;
		let boundaries = [];
		if (mode === "时") {
			// 小时
			let {
				hourStart
			} = vk.pubfn.getCommonTime(new Date());
			// 在今日的时间上往前推24小时
			for (let i = -1; i < 24; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(hourStart, {
					hours: i,
					mode: "before", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			timeFormat = "h时";
		} else if (mode === "日") {
			// 日
			let {
				todayStart
			} = vk.pubfn.getCommonTime();
			// 在今日的时间上往前推
			for (let i = -1; i < 28; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(todayStart, {
					day: i,
					mode: "before", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			timeFormat = "MM-dd";
		} else {
			// 月
			let {
				monthStart
			} = vk.pubfn.getCommonTime();
			// 在今日的时间上往前推12个月
			for (let i = -1; i < 12; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(monthStart, {
					month: i,
					mode: "before", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			timeFormat = "M月";
		}

		// 数组顺序反转（必须从小到大排序）
		boundaries.reverse();
		// 数据库查询
		let dbRes = await db
			.collection(dbName.user)
			.aggregate()
			.match({
				register_date: _.gte(boundaries[0]).lte(
					boundaries[boundaries.length - 1]
				),
			})
			.bucket({
				groupBy: "$register_date",
				boundaries,
				default: "other",
				output: {
					count: $.sum(1),
				},
			})
			.end();

		// 组装数据返回
		res.list = boundaries.map((groupItem) => {
			let findItem = dbRes.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);
			let value = findItem && findItem.count ? findItem.count : 0;
			return {
				value,
				text,
				group,
			};
		});
		// 删除最后一个数据
		res.list.pop();

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 用户登录统计,按日或月
	 * @url admin/business/kh.stats.getUserLoginCountGroup 前端调用的url参数地址
	 */
	getUserLoginCountGroup: async function(data) {
		let res = {
			code: 0,
			msg: "",
		};
		// 业务逻辑开始-----------------------------------------------------------
		let {
			mode = "日"
		} = data;
		let group = "登录用户数量";
		let timeFormat;
		let boundaries = [];
		if (mode === "时") {
			// 小时
			let {
				hourStart
			} = vk.pubfn.getCommonTime(new Date());
			// 在今日的时间上往前推24小时
			for (let i = -1; i < 24; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(hourStart, {
					hours: i,
					mode: "before", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			timeFormat = "h时";
		} else if (mode === "日") {
			// 日
			let {
				todayStart
			} = vk.pubfn.getCommonTime();
			// 在今日的时间上往前推
			for (let i = -1; i < 28; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(todayStart, {
					day: i,
					mode: "before", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			timeFormat = "MM-dd";
		} else {
			// 月
			let {
				monthStart
			} = vk.pubfn.getCommonTime();
			// 在今日的时间上往前推12个月
			for (let i = -1; i < 12; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(monthStart, {
					month: i,
					mode: "before", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			timeFormat = "M月";
		}

		// 数组顺序反转（必须从小到大排序）
		boundaries.reverse();
		// 数据库查询
		let dbRes = await db
			.collection(dbName.loginLog)
			.aggregate()
			.match({
				_add_time: _.gte(boundaries[0]).lte(boundaries[boundaries.length - 1]),
			})
			.bucket({
				groupBy: "$_add_time",
				boundaries,
				default: "other",
				output: {
					count: $.addToSet("$user_id"),
				},
			})
			.addFields({
				count: $.size("$count"),
			})
			.end();

		// 组装数据返回
		res.list = boundaries.map((groupItem) => {
			let findItem = dbRes.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);
			let value = findItem && findItem.count ? findItem.count : 0;
			return {
				value,
				text,
				group,
			};
		});
		// 删除最后一个数据
		res.list.pop();

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},

	detailUserPie: async function() {
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		let total = await vk.baseDao.count({
			dbName: dbName.user,
		});
		let shifu = await vk.baseDao.count({
			dbName: dbName.user,
			whereJson: {
				identity: 1
			},
		});
		let agent = await vk.baseDao.count({
			dbName: dbName.user,
			whereJson: {
				identity: 2
			},
		});
		res.data = [{
				name: "一般用户",
				value: total - shifu - agent
			},
			{
				name: "师傅",
				value: shifu
			},
			{
				name: "代理商",
				value: agent
			},
		];
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 性别比例
	 * @url admin/business/kh.stats.getUserGenderCountGroup 前端调用的url参数地址
	 */
	getUserGenderCountGroup: async function(data) {
		let res = {
			code: 0,
			msg: "",
		};
		// 业务逻辑开始-----------------------------------------------------------
		let list = await vk.baseDao.selects({
			dbName: dbName.user,
			pageIndex: 1,
			pageSize: 10,
			getMain: true,
			// 主表where条件
			whereJson: {},
			groupJson: {
				_id: "$gender", // _id是分组id， $ 后面接字段名，如user_id字段进行分组
				count: _.$.sum(1), // $ 后面接字段名，sum(1)代表求记录数量
			},
		});
		let boundaries = ["未知", "男", "女"];
		// 组装数据返回
		res.data = boundaries.map((groupItem, groupIndex) => {
			let findItem = list.find((item) => {
				if (!groupIndex && !item._id) {
					return true;
				}
				return item._id === groupIndex;
			});
			let text = groupItem;
			let value = findItem && findItem.count ? findItem.count : 0;
			return {
				value,
				name: text,
			};
		});
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 会员等级人数统计
	 * @url admin/business/kh.stats.getVipLvCountGroup 前端调用的url参数地址
	 */
	getVipLvCountGroup: async function(data) {
		let res = {
			code: 0,
			msg: "",
		};
		// 业务逻辑开始-----------------------------------------------------------
		let list = await vk.baseDao.selects({
			dbName: dbName.user,
			pageIndex: 1,
			pageSize: 100,
			getMain: true,
			// 主表where条件
			whereJson: {},
			groupJson: {
				_id: "$vip_lv", // _id是分组id， $ 后面接字段名，如user_id字段进行分组
				count: _.$.sum(1), // $ 后面接字段名，sum(1)代表求记录数量
			},
		});
		let mchInfo = await vk.daoCenter.mchDao.find();
		let {
			vip_level_rule
		} = mchInfo;

		// 组装数据返回
		res.list = vip_level_rule.map((groupItem, groupIndex) => {
			let findItem = list.find((item) => {
				return item._id === groupItem.lv;
			});
			let text = groupItem.name;
			let value = findItem && findItem.count ? findItem.count : 0;
			return {
				value,
				text,
			};
		});
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 分销等级人数统计
	 * @url admin/business/kh.stats.getFxLvCountGroup 前端调用的url参数地址
	 */
	getFxLvCountGroup: async function(data) {
		let res = {
			code: 0,
			msg: "",
		};
		// 业务逻辑开始-----------------------------------------------------------
		let list = await vk.baseDao.selects({
			dbName: dbName.user,
			pageIndex: 1,
			pageSize: 100,
			getMain: true,
			// 主表where条件
			whereJson: {},
			groupJson: {
				_id: "$fx.lv", // _id是分组id， $ 后面接字段名，如user_id字段进行分组
				count: _.$.sum(1), // $ 后面接字段名，sum(1)代表求记录数量
			},
		});
		let mchInfo = await vk.daoCenter.mchDao.find();
		let {
			level_rule
		} = mchInfo.fx;

		// 组装数据返回
		res.list = level_rule.map((groupItem, groupIndex) => {
			let findItem = list.find((item) => {
				return item._id === groupItem.lv;
			});
			let text = groupItem.name;
			let value = findItem && findItem.count ? findItem.count : 0;
			return {
				value,
				text,
			};
		});

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 订单统计,按日或月
	 * @url admin/business/kh.stats.getOrderCountGroup 前端调用的url参数地址
	 */
	getOrderCountGroup: async function(data) {
		let res = {
			code: 0,
			msg: "",
		};
		// 业务逻辑开始-----------------------------------------------------------
		let {
			mode = "日"
		} = data;
		let group = "支付订单数量";
		let timeFormat;
		let boundaries = [];
		if (mode === "时") {
			// 小时
			let {
				hourStart
			} = vk.pubfn.getCommonTime(new Date());
			// 在今日的时间上往前推24小时
			for (let i = -1; i < 24; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(hourStart, {
					hours: i,
					mode: "before", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			timeFormat = "h时";
		} else if (mode === "日") {
			// 日
			let {
				todayStart
			} = vk.pubfn.getCommonTime();
			// 在今日的时间上往前推
			for (let i = -1; i < 28; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(todayStart, {
					day: i,
					mode: "before", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			timeFormat = "MM-dd";
		} else {
			// 月
			let {
				monthStart
			} = vk.pubfn.getCommonTime();
			// 在今日的时间上往前推12个月
			for (let i = -1; i < 12; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(monthStart, {
					month: i,
					mode: "before", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			timeFormat = "M月";
		}

		// 数组顺序反转（必须从小到大排序）
		boundaries.reverse();
		// 数据库查询
		let dbRes = await db
			.collection(dbName.order)
			.aggregate()
			.match({
				status: _.gt(0),
				pay_time: _.gte(boundaries[0]).lte(boundaries[boundaries.length - 1]),
			})
			.bucket({
				groupBy: "$pay_time",
				boundaries,
				default: "other",
				output: {
					count: $.sum(1),
				},
			})
			.end();

		// 组装数据返回
		res.list = boundaries.map((groupItem) => {
			let findItem = dbRes.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);
			let value = findItem && findItem.count ? findItem.count : 0;
			return {
				value,
				text,
				group,
			};
		});
		// 删除最后一个数据
		res.list.pop();

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},

	/**
	 * 订单统计,按日或月
	 * @url admin/business/kh.stats.getOrderCountGroup 前端调用的url参数地址
	 */
	getOrderMyCountGroup: async function(data) {
		let res = {
			code: 0,
			msg: "",
		};
		// 业务逻辑开始-----------------------------------------------------------
		let {
			type = "week"
		} = data;
		let group = "支付订单数量";
		let timeFormat;
		let boundaries = [];
		if (type == "week") {
			// 周
			let {
				weekStart
			} = vk.pubfn.getCommonTime();
			console.log(weekStart);
			// 在今日的时间上往前推12个月
			for (let i = 0; i <= 7; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(weekStart, {
					day: i,
					mode: "after", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			timeFormat = "yyyy-MM-dd";
		} else if (type == "month") {
			// 月
			let {
				monthStart
			} = vk.pubfn.getCommonTime();
			//计算这个月有多少天，yearStart为时间戳
			var date = new Date(monthStart * 1000); // 注意，JS 的 Date 需要毫秒级的时间戳，所以需要乘以1000
			var year = date.getFullYear();
			var month = date.getMonth();

			var nextMonth = new Date(year, month + 1, 1); // 获取下个月的第一天
			nextMonth.setDate(nextMonth.getDate() - 1); // 减去一天，得到当前月的最后一天

			var daysInMonth = nextMonth.getDate(); // 获取这个月的天数

			for (let i = 0; i <= daysInMonth; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(monthStart, {
					day: i,
					mode: "after", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			timeFormat = "yyyy-MM-dd";
		} else {
			// 季度
			let {
				yearStart
			} = vk.pubfn.getCommonTime();
			// 在今日的时间上往前推4个季度
			for (let i = 0; i <= 12; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(yearStart, {
					month: i,
					mode: "after", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			//删除最后一个
			timeFormat = "yyyy-MM";
		}

		// 数组顺序反转（必须从小到大排序）
		// boundaries.reverse();
		console.log(boundaries);
		// 数据库查询
		let dbRes = await db
			.collection(dbName.order)
			.aggregate()
			.match({
				status: _.gt(0),
				pay_time: _.gte(boundaries[0]).lte(boundaries[boundaries.length - 1]),
			})
			.bucket({
				groupBy: "$pay_time",
				boundaries,
				default: "other",
				output: {
					count: $.sum(1),
				},
			})
			.end();

		//订单销售额
		let dbRes2 = await db
			.collection(dbName.order)
			.aggregate()
			.match({
				status: _.gt(0),
				pay_time: _.gte(boundaries[0]).lte(boundaries[boundaries.length - 1]),
			})
			.bucket({
				groupBy: "$pay_time",
				boundaries,
				default: "other",
				output: {
					count: $.sum("$amount_info.payment_amount"),
				},
			})
			.end();

		//订单利润
		let dbRes3 = await db
			.collection(dbName.order)
			.aggregate()
			.match({
				status: _.gt(0),
				pay_time: _.gte(boundaries[0]).lte(boundaries[boundaries.length - 1]),
			})
			.bucket({
				groupBy: "$pay_time",
				boundaries,
				default: "other",
				output: {
					count: $.sum("$amount_info.profit"),
				},
			})
			.end();

		// 组装数据返回
		res.list = boundaries.map((groupItem, index) => {
			let findItem = dbRes.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);
			if (type == "week") {
				text = "周" + this.numStr(index + 1);
				if (index == 6) {
					text = "周日";
				}
			} else if (type == "month") {
				text = index + 1 + "号";
			} else {
				text = this.numStr(index + 1) + "月";
			}

			let value = findItem && findItem.count ? findItem.count : 0;
			return {
				value,
				text,
				group,
			};
		});
		res.list2 = boundaries.map((groupItem, index) => {
			let findItem = dbRes2.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);
			if (type == "week") {
				text = "周" + this.numStr(index + 1);
				if (index == 6) {
					text = "周日";
				}
			} else if (type == "month") {
				text = index + 1 + "号";
			} else {
				text = this.numStr(index + 1) + "月";
			}

			let value = vk.pubfn.priceFilter(
				findItem && findItem.count ? findItem.count : 0
			);
			return {
				value,
				text,
				group,
			};
		});

		res.list3 = boundaries.map((groupItem, index) => {
			let findItem = dbRes3.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);
			if (type == "week") {
				text = "周" + this.numStr(index + 1);
				if (index == 6) {
					text = "周日";
				}
			} else if (type == "month") {
				text = index + 1 + "号";
			} else {
				text = this.numStr(index + 1) + "月";
			}

			let value = vk.pubfn.priceFilter(
				findItem && findItem.count ? findItem.count : 0
			);
			return {
				value,
				text,
				group,
			};
		});
		// 删除最后一个数据
		res.list.pop();
		res.list2.pop();
		res.list3.pop();

		//

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},

	detailGoodView: async function(data) {
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		let {
			time = []
		} = data;
		let list = [{
				icon: "vk-icon-goodsfill",
				color: "#1890ff",
				title: "商品浏览量",
				content: "在选定条件下，所有商品详情页被访问的次数，一个人在统计时间内访问多次记为多次",
				value: 0,
				value2: 0,
			},
			{
				icon: "el-icon-s-shop",
				color: "#00c050",
				title: "商品访客数",
				content: "在选定条件下，访问任何商品详情页的人数，一个人在统计时间范围内访问多次只记为一个",
				value: 0,
				value2: 0,
			},
			//加购件数
			{
				icon: "vk-icon-cart_fill_light",
				color: "#ffab2b",
				title: "加购件数",
				content: "在选定条件下，在选定条件下，添加商品进入购物车的商品件数",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-order",
				color: "#b37feb",
				title: "下单件数",
				content: "在选定条件下，成功下单的商品件数之和（不剔除退款订单）",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-pay",
				color: "#1890ff",
				title: "支付件数",
				content: "在选定条件下，成功付款订单的商品件数之和（线下支付订单在后台确认支付后计入，不剔除退款订单））",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-moneybagfill",
				color: "#00c050",
				title: "支付金额",
				content: "在选定条件下，成功付款订单的商品金额之和（线下支付订单在后台确认支付后计入，不剔除退款订单）",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-moneybag",
				color: "#ffab2b",
				title: "成本金额",
				content: "在选定条件下，成功付款订单的商品成本金额之和",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-return",
				color: "#b37feb",
				title: "退款金额",
				content: "在选定条件下，成功下单的商品件数之和（线下支付订单在后台确认支付后计入，不剔除退款订单）",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-goods_new_fill_light",
				color: "#1890ff",
				title: "退款件数",
				content: "在选定条件下，成功退款的商品件数之和",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-moneybagfill",
				color: "#00c050",
				title: "访客-支付转化率",
				content: "在选定条件下， 付款人数 / 访客数",
				value: 0,
				value2: 0,
			},
		];
		//计算time[0]he time[1]之间相差多少天
		let days = this.getDaysBetween(time[0], time[1]);
		let time2 = [0, 0];
		time2[1] = vk.pubfn.getDayOffsetStartAndEnd(-1, new Date(time[0])).endTime;
		time2[0] = vk.pubfn.getDayOffsetStartAndEnd(
			-days,
			new Date(time[1])
		).startTime;

		console.log("time2", time2);
		console.log("time", time);
		//获取商品浏览量
		let goodView1 = await vk.daoCenter.goodsBrowsingDao.count({
			_add_time: _.gte(time[0]).lte(time[1]),
		});
		let goodView2 = await vk.daoCenter.goodsBrowsingDao.count({
			_add_time: _.gte(time2[0]).lte(time2[1]),
		});
		list[0].value = goodView1;
		list[0].value2 = goodView2;

		res.list = list;

		//获取商品访客数
		let goodVisitor1 = await vk.baseDao.selects({
			dbName: "vk-goods-browsing",
			pageIndex: 1,
			pageSize: 1,
			getCount: true,
			// 主表where条件
			whereJson: {
				user_id: _.neq(""),
				_add_time: _.gte(time[0]).lte(time[1]),
			},
			groupJson: {
				_id: "$user_id", // _id是分组id（_id:为固定写法，必填属性），这里指按user_id字段进行分组

				count: _.$.sum(1), // count记录条数
			},
		});
		let goodVisitor2 = await vk.baseDao.selects({
			dbName: "vk-goods-browsing",
			pageIndex: 1,
			pageSize: 1,
			getCount: true,
			// 主表where条件
			whereJson: {
				user_id: _.neq(""),
				_add_time: _.gte(time2[0]).lte(time2[1]),
			},
			groupJson: {
				_id: "$user_id", // _id是分组id（_id:为固定写法，必填属性），这里指按user_id字段进行分组
				count: _.$.sum(1), // count记录条数
			},
		});
		console.log("goodVisitor1", goodVisitor1);
		list[1].value = goodVisitor1.total;
		list[1].value2 = goodVisitor2.total;

		//获取商品加购件数
		let goodAddCart1 = await vk.daoCenter.cartDao.sum({
			fieldName: "buy_num",
			whereJson: {
				_add_time: _.gte(time[0]).lte(time[1]),
			},
		});
		let goodAddCart2 = await vk.daoCenter.cartDao.sum({
			fieldName: "buy_num",
			whereJson: {
				_add_time: _.gte(time2[0]).lte(time2[1]),
			},
		});
		list[2].value = goodAddCart1;
		list[2].value2 = goodAddCart2;

		//下单件数
		let orderNum1 = await vk.daoCenter.orderDao.sum({
			fieldName: "buy_num",
			whereJson: {
				_add_time: _.gte(time[0]).lte(time[1]),
				status: _.neq(-1),
			},
		});
		let orderNum2 = await vk.daoCenter.orderDao.sum({
			fieldName: "buy_num",
			whereJson: {
				_add_time: _.gte(time2[0]).lte(time2[1]),
				status: _.neq(-1),
			},
		});
		list[3].value = orderNum1;
		list[3].value2 = orderNum2;

		//支付件数
		let payNum1 = await vk.daoCenter.orderDao.sum({
			fieldName: "buy_num",
			whereJson: {
				pay_time: _.gte(time[0]).lte(time[1]),
			},
		});
		let payNum2 = await vk.daoCenter.orderDao.sum({
			fieldName: "buy_num",
			whereJson: {
				pay_time: _.gte(time2[0]).lte(time2[1]),
			},
		});
		list[4].value = payNum1;
		list[4].value2 = payNum2;

		//支付金额
		let payMoney1 = await vk.daoCenter.orderDao.sum({
			fieldName: "amount_info.payment_amount",
			whereJson: {
				pay_time: _.gte(time[0]).lte(time[1]),
			},
		});
		let payMoney2 = await vk.daoCenter.orderDao.sum({
			fieldName: "amount_info.payment_amount",
			whereJson: {
				pay_time: _.gte(time2[0]).lte(time2[1]),
			},
		});
		list[5].value = vk.pubfn.priceFilter(payMoney1);
		list[5].value2 = vk.pubfn.priceFilter(payMoney2);

		//成本金额
		let costMoney1 = await vk.daoCenter.orderDao.sum({
			fieldName: "amount_info.profit",
			whereJson: {
				pay_time: _.gte(time[0]).lte(time[1]),
			},
		});
		let costMoney2 = await vk.daoCenter.orderDao.sum({
			fieldName: "amount_info.profit",
			whereJson: {
				pay_time: _.gte(time2[0]).lte(time2[1]),
			},
		});
		list[6].value = vk.pubfn.priceFilter(payMoney1 - costMoney1);
		list[6].value2 = vk.pubfn.priceFilter(payMoney2 - costMoney2);

		//退款金额
		let refundMoney1 = await vk.daoCenter.orderDao.sum({
			fieldName: "amount_info.refund_amount",
			whereJson: {
				refund_time: _.gte(time[0]).lte(time[1]),
			},
		});
		let refundMoney2 = await vk.daoCenter.orderDao.sum({
			fieldName: "amount_info.refund_amount",
			whereJson: {
				refund_time: _.gte(time2[0]).lte(time2[1]),
			},
		});

		list[7].value = vk.pubfn.priceFilter(refundMoney1);
		list[7].value2 = vk.pubfn.priceFilter(refundMoney2);

		//退款件数
		let refundNum1 = await vk.daoCenter.orderDao.sum({
			fieldName: "refund_num",
			whereJson: {
				_add_time: _.gte(time[0]).lte(time[1]),
			},
		});
		let refundNum2 = await vk.daoCenter.orderDao.sum({
			fieldName: "refund_num",
			whereJson: {
				_add_time: _.gte(time2[0]).lte(time2[1]),
			},
		});
		list[8].value = refundNum1;
		list[8].value2 = refundNum2;

		//获取支付人数
		let payVisitor1 = await vk.baseDao.selects({
			dbName: "vk-mall-order",
			pageIndex: 1,
			pageSize: 500,
			// 主表where条件
			whereJson: {
				user_id: _.neq(""),
				_add_time: _.gte(time[0]).lte(time[1]),
				status: _.gte(1),
			},
			groupJson: {
				_id: "$user_id", // _id是分组id（_id:为固定写法，必填属性），这里指按user_id字段进行分组
				count: _.$.sum(1), // count记录条数
			},
		});
		let payVisitor2 = await vk.baseDao.selects({
			dbName: "vk-mall-order",
			pageIndex: 1,
			pageSize: 500,
			// 主表where条件
			whereJson: {
				user_id: _.neq(""),
				_add_time: _.gte(time2[0]).lte(time2[1]),
				status: _.gte(1),
			},
			groupJson: {
				_id: "$user_id", // _id是分组id（_id:为固定写法，必填属性），这里指按user_id字段进行分组
				count: _.$.sum(1), // count记录条数
			},
		});
		let payPeopleNum1 = payVisitor1.total;
		let payPeopleNum2 = payVisitor2.total;

		//访客-支付转化率
		let payRate1 = (payPeopleNum1 / goodVisitor1.total) * 100;
		let payRate2 = (payPeopleNum2 / goodVisitor2.total) * 100;
		if (isNaN(payRate1)) {
			payRate1 = 0;
		}
		if (isNaN(payRate2)) {
			payRate2 = 0;
		}
		list[9].value = payRate1.toFixed(2);
		list[9].value2 = payRate2.toFixed(2) || 0;
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},

	detailOrderView: async function(data) {
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		let {
			time = []
		} = data;
		let list = [{
				icon: "vk-icon-sponsor",
				color: "#1890ff",
				title: "营业额",
				content: "在选定条件下，商品支付金额、充值金额（后续预留）、购买付费会员金额（后续预留）、线下收银金额（后续预留）",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-moneybagfill",
				color: "#00c050",
				title: "交易净收入金额",
				content: "在选定条件下，交易净收入金额 = 营业额 - 支出金额",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-cart_fill_light",
				color: "#ffab2b",
				title: "商品支付金额",
				content: "选定条件下，用户购买商品的实际支付金额，包括微信支付、余额支付、支付宝支付、线下支付金额",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-order",
				color: "#b37feb",
				title: "充值金额",
				content: "选定条件下，用户成功充值的金额，只包含用户使用支付宝和微信充值的金额（后续预留）",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-pay",
				color: "#1890ff",
				title: "支出金额",
				content: "在选定条件下，余额支付金额、支付佣金金额、商品退款金额",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-ticket_money_fill",
				color: "#00c050",
				title: "余额支付金额",
				content: "在选定条件下，用户下单时使用余额实际支付的金额",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-moneybag",
				color: "#ffab2b",
				title: "支付佣金金额",
				content: "平台给业务员支付的推广佣金，以实际到账为准",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-refund",
				color: "#b37feb",
				title: "商品退款金额",
				content: "在选定条件下，用户成功退款的商品金额",
				value: 0,
				value2: 0,
			},
		];
		//计算time[0]he time[1]之间相差多少天
		let days = this.getDaysBetween(time[0], time[1]);
		let time2 = [0, 0];
		time2[1] = vk.pubfn.getDayOffsetStartAndEnd(-1, new Date(time[0])).endTime;
		time2[0] = vk.pubfn.getDayOffsetStartAndEnd(
			-days,
			new Date(time[1])
		).startTime;

		console.log("time2", time2);
		console.log("time", time);
		//商品支付金额
		let goodPay1 = await vk.daoCenter.orderDao.sum({
			fieldName: "amount_info.payment_amount",
			whereJson: {
				pay_time: _.gte(time[0]).lte(time[1]),
			},
		});
		let goodPay2 = await vk.daoCenter.orderDao.sum({
			fieldName: "amount_info.payment_amount",
			whereJson: {
				pay_time: _.gte(time2[0]).lte(time2[1]),
			},
		});
		list[2].value = vk.pubfn.priceFilter(goodPay1);
		list[2].value2 = vk.pubfn.priceFilter(goodPay2);
		console.log("goodPay1", goodPay1);

		//充值金额
		let recharge1 = await vk.daoCenter.orderRechargeDao.sum({
			fieldName: "payment_amount",
			whereJson: {
				pay_time: _.gte(time[0]).lte(time[1]),
			},
		});
		let recharge2 = await vk.daoCenter.orderRechargeDao.sum({
			fieldName: "payment_amount",
			whereJson: {
				pay_time: _.gte(time2[0]).lte(time2[1]),
			},
		});
		list[3].value = vk.pubfn.priceFilter(recharge1);
		list[3].value2 = vk.pubfn.priceFilter(recharge2);
		//营业额
		list[0].value = vk.pubfn.priceFilter(goodPay1 + recharge1);
		list[0].value2 = vk.pubfn.priceFilter(goodPay2 + recharge2);
		console.log("list[0].value", list[0].value, goodPay1);

		//余额支付金额
		let balancePay1 = await vk.daoCenter.orderDao.sum({
			fieldName: "amount_info.used_balance_amount",
			whereJson: {
				pay_time: _.gte(time[0]).lte(time[1]),
			},
		});
		let balancePay2 = await vk.daoCenter.orderDao.sum({
			fieldName: "amount_info.used_balance_amount",
			whereJson: {
				pay_time: _.gte(time2[0]).lte(time2[1]),
			},
		});
		list[5].value = vk.pubfn.priceFilter(balancePay1);
		list[5].value2 = vk.pubfn.priceFilter(balancePay2);

		//支付佣金金额
		let payCommission1 = await vk.daoCenter.rewardRecDao.sum({
			fieldName: "value",
			whereJson: {
				_add_time: _.gte(time[0]).lte(time[1]),
				type: 1,
				is_freeze: false,
			},
		});
		let payCommission2 = await vk.daoCenter.rewardRecDao.sum({
			fieldName: "value",
			whereJson: {
				_add_time: _.gte(time2[0]).lte(time2[1]),
				type: 1,
				is_freeze: false,
			},
		});
		list[6].value = vk.pubfn.priceFilter(payCommission1);
		list[6].value2 = vk.pubfn.priceFilter(payCommission2);

		//商品退款金额
		let refund1 = await vk.daoCenter.orderDao.sum({
			fieldName: "amount_info.refund_amount",
			whereJson: {
				refund_time: _.gte(time[0]).lte(time[1]),
			},
		});
		let refund2 = await vk.daoCenter.orderDao.sum({
			fieldName: "amount_info.refund_amount",
			whereJson: {
				refund_time: _.gte(time2[0]).lte(time2[1]),
			},
		});
		console.log("refund1", refund1);

		list[7].value = vk.pubfn.priceFilter(refund1);
		list[7].value2 = vk.pubfn.priceFilter(refund2);

		//支出金额
		list[4].value = vk.pubfn.priceFilter(
			payCommission1 + refund1 + balancePay1
		);
		list[4].value2 = vk.pubfn.priceFilter(
			payCommission2 + refund2 + balancePay2
		);

		//交易毛利
		list[1].value = vk.pubfn.toDecimal(list[0].value - list[4].value, 2);

		list[1].value2 = vk.pubfn.toDecimal(list[0].value2 - list[4].value2, 2);
		res.list = list;
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},

	/**
	 * 订单统计,按日或月
	 * @url admin/business/kh.stats.getOrderCountGroup 前端调用的url参数地址
	 */
	detailOrderChart: async function(data) {
		let res = {
			code: 0,
			msg: "",
		};
		// 业务逻辑开始-----------------------------------------------------------
		let {
			time = []
		} = data;
		let group = "支付订单数量";
		let timeFormat;
		let boundaries = [];
		let days = this.getDaysBetween(time[0], time[1]);
		console.log(days);
		if (days > 1) {
			// 周
			// 在今日的时间上往前推12个月
			for (let i = 0; i <= days; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(time[0], {
					day: i,
					mode: "after", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			timeFormat = "yyyy-MM-dd";
		} else {
			//24小时
			for (let i = 0; i <= 24; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(time[0], {
					hour: i,
					mode: "after", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			timeFormat = "hh";
		}

		// 数组顺序反转（必须从小到大排序）
		// boundaries.reverse();
		console.log(boundaries);
		// 商品支付金额
		let dbRes = await db
			.collection("vk-mall-order")
			.aggregate()
			.match({
				pay_time: _.gte(boundaries[0]).lte(boundaries[boundaries.length - 1]),
			})
			.bucket({
				groupBy: "$pay_time",
				boundaries,
				default: "other",
				output: {
					count: $.sum("$amount_info.payment_amount"),
				},
			})
			.end();
		// 充值金额
		let dbRes2 = await db
			.collection("vk-mall-order-recharge")
			.aggregate()
			.match({
				pay_time: _.gte(boundaries[0]).lte(boundaries[boundaries.length - 1]),
			})
			.bucket({
				groupBy: "$pay_time",
				boundaries,
				default: "other",
				output: {
					count: $.sum("$payment_amount"),
				},
			})
			.end();

		//余额支付金额
		let dbRes3 = await db
			.collection("vk-mall-order")
			.aggregate()
			.match({
				pay_time: _.gte(boundaries[0]).lte(boundaries[boundaries.length - 1]),
			})
			.bucket({
				groupBy: "$pay_time",
				boundaries,
				default: "other",
				output: {
					count: $.sum("$amount_info.used_balance_amount"),
				},
			})
			.end();

		//支付佣金金额
		let dbRes4 = await db
			.collection("vk-user-reward-rec")
			.aggregate()
			.match({
				_add_time: _.gte(boundaries[0]).lte(boundaries[boundaries.length - 1]),
				type: 1,
				is_freeze: false,
			})
			.bucket({
				groupBy: "$_add_time",
				boundaries,
				default: "other",
				output: {
					count: $.sum("$value"),
				},
			})
			.end();
		console.log(222222, dbRes4);

		//退款金额
		let dbRes5 = await db
			.collection("vk-mall-order")
			.aggregate()
			.match({
				refund_time: _.gte(boundaries[0]).lte(
					boundaries[boundaries.length - 1]
				),
			})
			.bucket({
				groupBy: "$refund_time",
				boundaries,
				default: "other",
				output: {
					count: $.sum("$amount_info.refund_amount"),
				},
			})
			.end();

		// 组装数据返回
		res.list = boundaries.map((groupItem, index) => {
			let findItem = dbRes.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);
			let value = findItem && findItem.count ? findItem.count : 0;
			return {
				value: vk.pubfn.priceFilter(value),
				text,
				group,
			};
		});
		res.list2 = boundaries.map((groupItem, index) => {
			let findItem = dbRes2.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);

			let value = findItem && findItem.count ? findItem.count : 0;

			return {
				value: vk.pubfn.priceFilter(value),
				text,
				group,
			};
		});

		//营业额 = 商品支付金额 + 充值金额

		res.list3 = boundaries.map((groupItem, index) => {
			let findItem = dbRes.data.find((item) => {
				return item._id === groupItem;
			});
			let findItem2 = dbRes2.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);
			let value = findItem && findItem.count ? findItem.count : 0;
			let value2 = findItem2 && findItem2.count ? findItem2.count : 0;
			return {
				value: vk.pubfn.priceFilter(value + value2),
				text,
				group,
			};
		});

		//支出金额 = 余额支付金额 + 支付佣金金额 + 退款金额

		res.list4 = boundaries.map((groupItem, index) => {
			let findItem = dbRes3.data.find((item) => {
				return item._id === groupItem;
			});
			let findItem2 = dbRes4.data.find((item) => {
				return item._id === groupItem;
			});
			let findItem3 = dbRes5.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);
			let value = findItem && findItem.count ? findItem.count : 0;
			let value2 = findItem2 && findItem2.count ? findItem2.count : 0;
			let value3 = findItem3 && findItem3.count ? findItem3.count : 0;
			return {
				value: vk.pubfn.priceFilter(value + value2 + value3),
				text,
				group,
			};
		});

		//交易毛利 = 营业额 - 支出金额

		res.list5 = boundaries.map((groupItem, index) => {
			let findItem = dbRes.data.find((item) => {
				return item._id === groupItem;
			});
			let findItem2 = dbRes2.data.find((item) => {
				return item._id === groupItem;
			});
			let findItem3 = dbRes3.data.find((item) => {
				return item._id === groupItem;
			});
			let findItem4 = dbRes4.data.find((item) => {
				return item._id === groupItem;
			});
			let findItem5 = dbRes5.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);
			let value = findItem && findItem.count ? findItem.count : 0;
			let value2 = findItem2 && findItem2.count ? findItem2.count : 0;
			let value3 = findItem3 && findItem3.count ? findItem3.count : 0;
			let value4 = findItem4 && findItem4.count ? findItem4.count : 0;
			let value5 = findItem5 && findItem5.count ? findItem5.count : 0;
			return {
				value: vk.pubfn.priceFilter(
					value + value2 - (value3 + value4 + value5)
				),
				text,
				group,
			};
		});

		// 删除最后一个数据
		res.list.pop(); //商品支付金额
		res.list2.pop(); //充值金额
		res.list3.pop(); //营业额
		res.list4.pop(); //支出金额
		res.list5.pop(); //交易毛利

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},

	userView: async function(data) {
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		let {
			time = []
		} = data;
		let list = [{
				icon: "vk-icon-myfill",
				color: "#1890ff",
				title: "访客数",
				content: "在选定条件下，访问商城首页的去重人数",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-attention_light",
				color: "#00c050",
				title: "浏览量",
				content: "在选定条件下，用户浏览商城页面的次数。每打开一个页面或每刷新一次页面都记录1次",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-friendadd",
				color: "#ffab2b",
				title: "新增用户数",
				content: "在选定条件下，新注册的用户",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-friendfavor",
				color: "#b37feb",
				title: "成交用户数",
				content: "在选定条件下，下单并支付成功的用户",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-refresh",
				color: "#1890ff",
				title: "访客-支付转换率",
				content: "在选定条件下，全部成交客户数 / 商城访客数",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-vip",
				color: "#00c050",
				title: "会员人数",
				content: "在选定条件下，通过各种方式成为会员的用户数，不是普通用户",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-gudongfenhong",
				color: "#ffab2b",
				title: "客单价",
				content: "在选定条件下，用户支付的总金额 / 支付人数",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-friend",
				color: "#b37feb",
				title: "累计用户数",
				content: "筛选时间截止时，商城的总用户",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-friendfamous",
				color: "#1890ff",
				title: "累计成交用户数",
				content: "筛选时间截止时，下单并支付成功的用户",
				value: 0,
				value2: 0,
			},
			{
				icon: "vk-icon-group_fill",
				color: "#00c050",
				title: "累计会员数",
				content: "筛选时间截止时，具有商城会员身份的用户数",
				value: 0,
				value2: 0,
			},
		];
		//计算time[0]he time[1]之间相差多少天
		let days = this.getDaysBetween(time[0], time[1]);
		let time2 = [0, 0];
		time2[1] = vk.pubfn.getDayOffsetStartAndEnd(-1, new Date(time[0])).endTime;
		time2[0] = vk.pubfn.getDayOffsetStartAndEnd(
			-days,
			new Date(time[1])
		).startTime;

		console.log("time2", time2);
		console.log("time", time);

		//获取用户访客数
		let userVisitor1 = await vk.baseDao.selects({
			dbName: "vk-user-browsing",
			pageIndex: 1,
			pageSize: 1,
			getCount: true,
			// 主表where条件
			whereJson: {
				user_id: _.neq(""),
				_add_time: _.gte(time[0]).lte(time[1]),
			},
			groupJson: {
				_id: "$user_id", // _id是分组id（_id:为固定写法，必填属性），这里指按user_id字段进行分组
				count: _.$.sum(1), // count记录条数
			},
		});

		let userVisitor2 = await vk.baseDao.selects({
			dbName: "vk-user-browsing",
			pageIndex: 1,
			pageSize: 1,
			getCount: true,
			// 主表where条件
			whereJson: {
				user_id: _.neq(""),
				_add_time: _.gte(time2[0]).lte(time2[1]),
			},
			groupJson: {
				_id: "$user_id", // _id是分组id（_id:为固定写法，必填属性），这里指按user_id字段进行分组
				count: _.$.sum(1), // count记录条数
			},
		});
		list[0].value = userVisitor1.total;
		list[0].value2 = userVisitor2.total;

		//获取浏览量
		let viewCount1 = await vk.baseDao.count({
			dbName: "vk-user-browsing",
			// 主表where条件
			whereJson: {
				_add_time: _.gte(time[0]).lte(time[1]),
			},
		});
		let viewCount2 = await vk.baseDao.count({
			dbName: "vk-user-browsing",
			// 主表where条件
			whereJson: {
				_add_time: _.gte(time2[0]).lte(time2[1]),
			},
		});
		list[1].value = viewCount1;
		list[1].value2 = viewCount2;

		//获取新增用户数
		let newUser1 = await vk.daoCenter.userDao.count({
			register_date: _.gte(time[0]).lte(time[1]),
		});
		let newUser2 = await vk.daoCenter.userDao.count({
			register_date: _.gte(time2[0]).lte(time2[1]),
		});
		list[2].value = newUser1;
		list[2].value2 = newUser2;

		//获取成交客户数
		let payUser1 = await vk.baseDao.selects({
			dbName: "vk-mall-order",
			pageIndex: 1,
			pageSize: 1,
			getCount: true,
			// 主表where条件
			whereJson: {
				user_id: _.neq(""),
				pay_time: _.gte(time[0]).lte(time[1]),
			},
			groupJson: {
				_id: "$user_id", // _id是分组id（_id:为固定写法，必填属性），这里指按user_id字段进行分组
				count: _.$.sum(1), // count记录条数
			},
		});
		let payUser2 = await vk.baseDao.selects({
			dbName: "vk-mall-order",
			pageIndex: 1,
			pageSize: 1,
			getCount: true,
			// 主表where条件
			whereJson: {
				user_id: _.neq(""),
				pay_time: _.gte(time2[0]).lte(time2[1]),
			},
			groupJson: {
				_id: "$user_id", // _id是分组id（_id:为固定写法，必填属性），这里指按user_id字段进行分组
				count: _.$.sum(1), // count记录条数
			},
		});
		list[3].value = payUser1.total;
		list[3].value2 = payUser2.total;

		if (list[0].value == 0) {
			list[4].value = 0;
		} else {
			console.log("list[3].value", list[3].value, list[1].value);
			list[4].value = ((list[3].value / list[0].value) * 100).toFixed(2);
		}

		if (list[0].value2 == 0) {
			list[4].value2 = 0;
		} else {
			list[4].value2 = ((list[3].value2 / list[0].value2) * 100).toFixed(2);
		}

		//获取成交金额
		let payMoney1 = await vk.daoCenter.orderDao.sum({
			fieldName: "amount_info.payment_amount",
			whereJson: {
				status: _.gte(1),
				pay_time: _.gte(time[0]).lte(time[1]),
			},
		});
		let payMoney2 = await vk.daoCenter.orderDao.sum({
			fieldName: "amount_info.payment_amount",
			whereJson: {
				status: _.gte(1),
				pay_time: _.gte(time2[0]).lte(time2[1]),
			},
		});

		//获取会员数
		let member1 = await vk.daoCenter.userDao.count({

			vip_lv: _.gt(0),
			vip_get_time: _.gte(time[0]).lte(time[1]),
		});
		let member2 = await vk.daoCenter.userDao.count({

			vip_lv: _.gt(0),
			vip_get_time: _.gte(time2[0]).lte(time2[1]),
		});
		list[5].value = member1;
		list[5].value2 = member2;

		//获取客单价
		if (list[3].value == 0) {
			list[6].value = 0;
		} else {
			list[6].value = vk.pubfn.priceFilter(
				(payMoney1 / list[3].value).toFixed(2)
			);
		}

		if (list[3].value2 == 0) {
			list[6].value2 = 0;
		} else {
			list[6].value2 = vk.pubfn.priceFilter(
				(payMoney2 / list[3].value2).toFixed(2)
			);
		}

		//累计用户数
		let totalUser = await vk.daoCenter.userDao.count({

			register_date: _.lte(time[1]),
		});
		list[7].value = totalUser;
		list[7].value2 = totalUser;

		//累计成交客户数
		let totalPayUser = await vk.baseDao.selects({
			dbName: "vk-mall-order",
			pageIndex: 1,
			pageSize: 1,
			getCount: true,
			// 主表where条件
			whereJson: {
				user_id: _.neq(""),
				pay_time: _.lte(time[1]),
			},
			groupJson: {
				_id: "$user_id", // _id是分组id（_id:为固定写法，必填属性），这里指按user_id字段进行分组
				count: _.$.sum(1), // count记录条数
			},
		});
		list[8].value = totalPayUser.total;
		list[8].value2 = totalPayUser.total;

		//累计会员数
		let totalMember = await vk.daoCenter.userDao.count({
			vip_lv: _.gt(0),
			vip_get_time: _.lte(time[1]),
		});
		list[9].value = totalMember;
		list[9].value2 = totalMember;

		res.list = list;
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},

	queryGoodRank: async function(data) {
		let res = {
			code: 0,
			msg: "",
		};
		// 业务逻辑开始-----------------------------------------------------------
		let list = await vk.baseDao.select({
			dbName: dbName.goods,
			getCount: false,
			pageIndex: 1,
			pageSize: 20,
			getMain: true,
			whereJson: {
				status: 1,
			},
			sortArr: [{
				name: "view_count",
				type: "desc",
			}, ],
		});
		let ids = list.map((item) => item._id);

		//商品访客数
		let goodVisitor = await db
			.collection("vk-goods-browsing")
			.aggregate()
			.match({
				goods_id: _.in(ids),
			})
			.limit(10000)
			.group({
				_id: {
					goods_id: "$goods_id",
					user_id: "$user_id",
				},
				count: $.sum(1),
				goods_id: $.first("$goods_id"),
				_add_time: $.first("$_add_time"),
			})
			.end();

		console.log(goodVisitor);

		//加购件数
		let goodCart = await db
			.collection("vk-mall-goods-cart")
			.aggregate()
			.match({
				goods_id: _.in(ids),
			})
			.limit(10000)
			.group({
				_id: "$goods_id",
				count: $.sum("$buy_num"),
				goods_id: $.first("$goods_id"),
				_add_time: $.first("$_add_time"),
			})
			.end();

		//支付件数
		let goodOrder = await db
			.collection("vk-mall-order")
			.aggregate()
			.limit(10000)
			.unwind("$goods_sku_list")
			.match({
				"goods_sku_list.goods_id": _.in(ids),
				status: _.gte(1),
			})
			.group({
				_id: "$goods_sku_list.goods_id",
				count: $.sum("$goods_sku_list.buy_num"),
				pay_count: $.sum("$goods_sku_list.buy_num"),
				pay_money: $.sum("$goods_sku_list.total_amount"),
				total_profit: $.sum("$goods_sku_list.total_profit"),
				goods_id: $.first("$goods_sku_list.goods_id"),
				_add_time: $.first("$_add_time"),
			})
			.end();
		console.log(goodOrder);
		list.forEach((item) => {
			let visitor_count = 0;
			let add_cart_count = 0;
			let pay_count = 0;
			let pay_money = 0;
			let total_profit = 0;
			let profit_rate = 0;
			let visitor_pay_rate = 0;
			goodVisitor.data.forEach((item2) => {
				if (item._id == item2.goods_id) {
					visitor_count++;
				}
			});
			goodCart.data.forEach((item3) => {
				if (item._id == item3.goods_id) {
					add_cart_count += item3.count;
				}
			});
			goodOrder.data.forEach((item4) => {
				if (item._id == item4.goods_id) {
					pay_count += item4.pay_count;
					pay_money += item4.pay_money;
					total_profit += item4.total_profit;
				}
			});
			if (pay_money > 0) {
				profit_rate = (total_profit / pay_money) * 100;
			}
			if (visitor_count > 0) {
				visitor_pay_rate = (pay_count / visitor_count) * 100;
			}
			item.visitor_pay_rate = visitor_pay_rate.toFixed(2);
			item.profit_rate = profit_rate.toFixed(2);
			item.pay_count = pay_count;
			item.pay_money = pay_money;
			item.total_profit = total_profit;
			item.visitor_count = visitor_count;
			item.add_cart_count = add_cart_count;
		});

		res.data = list;
		return res;
	},

	getDaysBetween: function(begin, end) {
		let days = (end - begin) / (1000 * 60 * 60 * 24);
		days = Math.ceil(days);
		return days;
	},

	/**
	 * 订单统计,按日或月
	 * @url admin/business/kh.stats.getOrderCountGroup 前端调用的url参数地址
	 */
	detailGoodChart: async function(data) {
		let res = {
			code: 0,
			msg: "",
		};
		// 业务逻辑开始-----------------------------------------------------------
		let {
			time = []
		} = data;
		let group = "支付订单数量";
		let timeFormat;
		let boundaries = [];
		let days = this.getDaysBetween(time[0], time[1]);
		console.log(days);
		if (days > 1) {
			// 周
			// 在今日的时间上往前推12个月
			for (let i = 0; i <= days; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(time[0], {
					day: i,
					mode: "after", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			timeFormat = "MM-dd";
		} else {
			//24小时
			for (let i = 0; i <= 24; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(time[0], {
					hour: i,
					mode: "after", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			timeFormat = "hh";
		}

		// 数组顺序反转（必须从小到大排序）
		// boundaries.reverse();
		console.log(boundaries);
		// 数据库查询
		let dbRes = await db
			.collection("vk-goods-browsing")
			.aggregate()
			.match({
				_add_time: _.gte(boundaries[0]).lte(boundaries[boundaries.length - 1]),
			})
			.bucket({
				groupBy: "$_add_time",
				boundaries,
				default: "other",
				output: {
					count: $.sum(1),
				},
			})
			.end();

		//商品访客量
		let dbRes2 = await db
			.collection("vk-goods-browsing")
			.aggregate()
			.match({
				_add_time: _.gte(boundaries[0]).lte(boundaries[boundaries.length - 1]),
			})
			.group({
				_id: "$user_id",
				count: $.sum(1),
				_add_time: $.first("$_add_time"),
			})
			.bucket({
				groupBy: "$_add_time",
				boundaries,
				default: "other",
				output: {
					count: $.sum(1),
				},
			})
			.end();

		//订单支付金额
		let dbRes3 = await db
			.collection(dbName.order)
			.aggregate()
			.match({
				pay_time: _.gte(boundaries[0]).lte(boundaries[boundaries.length - 1]),
			})
			.bucket({
				groupBy: "$pay_time",
				boundaries,
				default: "other",
				output: {
					count: $.sum("$amount_info.payment_amount"),
				},
			})
			.end();

		//订单支付金额
		let dbRes4 = await db
			.collection(dbName.order)
			.aggregate()
			.match({
				refund_time: _.gte(boundaries[0]).lte(
					boundaries[boundaries.length - 1]
				),
			})
			.bucket({
				groupBy: "$refund_time",
				boundaries,
				default: "other",
				output: {
					count: $.sum("$amount_info.refund_amount"),
				},
			})
			.end();

		// 组装数据返回
		res.list = boundaries.map((groupItem, index) => {
			let findItem = dbRes.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);
			let value = findItem && findItem.count ? findItem.count : 0;
			return {
				value,
				text,
				group,
			};
		});
		res.list2 = boundaries.map((groupItem, index) => {
			let findItem = dbRes2.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);

			let value = findItem && findItem.count ? findItem.count : 0;

			return {
				value,
				text,
				group,
			};
		});

		res.list3 = boundaries.map((groupItem, index) => {
			let findItem = dbRes3.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);

			let value = vk.pubfn.priceFilter(
				findItem && findItem.count ? findItem.count : 0
			);
			return {
				value,
				text,
				group,
			};
		});

		res.list4 = boundaries.map((groupItem, index) => {
			let findItem = dbRes4.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);

			let value = vk.pubfn.priceFilter(
				findItem && findItem.count ? findItem.count : 0
			);
			return {
				value,
				text,

				group,
			};
		});

		// 删除最后一个数据
		res.list.pop();
		res.list2.pop();
		res.list3.pop();
		res.list4.pop();

		//

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},

	/**
	 * 订单统计,按日或月
	 * @url admin/business/kh.stats.getOrderCountGroup 前端调用的url参数地址
	 */
	detailUserChart: async function(data) {
		let res = {
			code: 0,
			msg: "",
		};
		// 业务逻辑开始-----------------------------------------------------------
		let {
			time = []
		} = data;
		let group = "支付订单数量";
		let timeFormat;
		let boundaries = [];
		let days = this.getDaysBetween(time[0], time[1]);
		console.log(days);
		if (days > 1) {
			// 周
			// 在今日的时间上往前推12个月
			for (let i = 0; i <= days; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(time[0], {
					day: i,
					mode: "after", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			timeFormat = "MM-dd";
		} else {
			//24小时
			for (let i = 0; i <= 24; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(time[0], {
					hour: i,
					mode: "after", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			timeFormat = "hh";
		}

		// 数组顺序反转（必须从小到大排序）
		// boundaries.reverse();
		console.log(boundaries);
		// 数据库查询
		let dbRes = await db
			.collection("uni-id-users")
			.aggregate()
			.match({
				register_date: _.gte(boundaries[0]).lte(
					boundaries[boundaries.length - 1]
				),
			})
			.bucket({
				groupBy: "$register_date",
				boundaries,
				default: "other",
				output: {
					count: $.sum(1),
				},
			})
			.end();

		//访客量
		let dbRes2 = await db
			.collection("vk-user-browsing")
			.aggregate()
			.match({
				_add_time: _.gte(boundaries[0]).lte(boundaries[boundaries.length - 1]),
			})
			.group({
				_id: "$user_id",
				count: $.sum(1),
				_add_time: $.first("$_add_time"),
			})
			.bucket({
				groupBy: "$_add_time",
				boundaries,
				default: "other",
				output: {
					count: $.sum(1),
				},
			})
			.end();

		//成交用户数
		let dbRes3 = await db
			.collection(dbName.order)
			.aggregate()
			.match({
				status: _.gt(0),
				pay_time: _.gte(boundaries[0]).lte(boundaries[boundaries.length - 1]),
			})
			.group({
				_id: "$user_id",
				count: $.sum(1),
				pay_time: $.first("$pay_time"),
			})
			.bucket({
				groupBy: "$pay_time",
				boundaries,
				default: "other",
				output: {
					count: $.sum(1),
				},
			})
			.end();

		//新增会员数
		let dbRes4 = await db
			.collection("uni-id-users")
			.aggregate()
			.match({
				vip_lv: _.gt(0),
				vip_get_time: _.gte(boundaries[0]).lte(
					boundaries[boundaries.length - 1]
				),
			})
			.bucket({
				groupBy: "$vip_get_time",
				boundaries,
				default: "other",
				output: {
					count: $.sum(1),
				},
			})
			.end();

		// 组装数据返回
		res.list = boundaries.map((groupItem, index) => {
			let findItem = dbRes.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);
			let value = findItem && findItem.count ? findItem.count : 0;
			return {
				value,
				text,
				group,
			};
		});
		res.list2 = boundaries.map((groupItem, index) => {
			let findItem = dbRes2.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);

			let value = findItem && findItem.count ? findItem.count : 0;

			return {
				value,
				text,
				group,
			};
		});

		res.list3 = boundaries.map((groupItem, index) => {
			let findItem = dbRes3.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);

			let value = findItem && findItem.count ? findItem.count : 0;

			return {
				value,
				text,
				group,
			};
		});

		res.list4 = boundaries.map((groupItem, index) => {
			let findItem = dbRes4.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);

			let value = findItem && findItem.count ? findItem.count : 0;

			return {
				value,
				text,
				group,
			};
		});

		// 删除最后一个数据
		res.list.pop();
		res.list2.pop();
		res.list3.pop();
		res.list4.pop();

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},

	/**
	 * 用户地域分布
	 */
	detailUserMap: async function() {
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		let selectRes = await vk.baseDao.selects({
			dbName: dbName.user,
			pageIndex: 1,
			pageSize: -1,
			getMain: true,
			whereJson: {},
			groupJson: {
				_id: "$province",
				count: _.$.sum(1),
				pay_amount: _.$.sum("$account_per.my_payment"),
			},
		});
		selectRes.forEach((item) => {
			item.pay_amount = vk.pubfn.priceFilter(item.pay_amount);
		});

		res.selectRes = selectRes;
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},

	/**
	 * 用户统计
	 */
	chartUserCount: async function() {
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		let timeFormat = "MM-dd";
		let boundaries = [];
		// 日
		let {
			todayStart
		} = vk.pubfn.getCommonTime();
		// 在今日的时间上往前推
		for (let i = -1; i < 28; i++) {
			let timeCalc = vk.pubfn.getOffsetTime(todayStart, {
				day: i,
				mode: "before",
			});
			boundaries.push(timeCalc);
		}
		// 数组顺序反转（必须从小到大排序）
		boundaries.reverse();
		// 数据库查询
		let dbRes = await db
			.collection(dbName.user)
			.aggregate()
			.match({
				register_date: _.gte(boundaries[0]).lte(
					boundaries[boundaries.length - 1]
				),

			})
			.bucket({
				groupBy: "$register_date",
				boundaries,
				default: "other",
				output: {
					count: $.sum(1)
				},
			})
			.end();
		// 组装数据返回
		res.list = boundaries.map((groupItem) => {
			let findItem = dbRes.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);
			let value = findItem && findItem.count ? findItem.count : 0;
			return {
				value,
				text
			};
		});
		// 删除最后一个数据
		res.list.pop();
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 用户消费
	 */
	chartUserPay: async function() {
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		let num = await vk.baseDao.count({
			dbName: dbName.user,
			whereJson: {},
		});
		let num2 = await vk.baseDao.count({
			dbName: dbName.user,
			whereJson: {
				buy: 1
			},
		});
		let num3 = await vk.baseDao.count({
			dbName: dbName.user,
			whereJson: {
				buy: _.gt(1)
			},
		});
		res.list = [num2, num3, num - num2 - num3];
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	//把数字转换成一，二，三等
	numStr: function(num) {
		var str = "";
		switch (num) {
			case 1:
				str = "一";
				break;
			case 2:
				str = "二";
				break;
			case 3:
				str = "三";
				break;
			case 4:
				str = "四";
				break;
			case 5:
				str = "五";
				break;
			case 6:
				str = "六";
				break;
			case 7:
				str = "七";
				break;
			case 8:
				str = "八";
				break;
			case 9:
				str = "九";
				break;
			case 10:
				str = "十";
				break;
			case 11:
				str = "十一";
				break;
			case 12:
				str = "十二";
				break;
		}
		return str;
	},
	/**
	 * 订单统计,按日或月(退款)
	 * @url admin/business/kh.stats.getRefundOrderCountGroup 前端调用的url参数地址
	 */
	getRefundOrderCountGroup: async function(data) {
		let res = {
			code: 0,
			msg: "",
		};
		// 业务逻辑开始-----------------------------------------------------------
		let {
			mode = "日"
		} = data;
		let group = "退款订单数量";
		let timeFormat;
		let boundaries = [];
		if (mode === "时") {
			// 小时
			let {
				hourStart
			} = vk.pubfn.getCommonTime(new Date());
			// 在今日的时间上往前推24小时
			for (let i = -1; i < 24; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(hourStart, {
					hours: i,
					mode: "before", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			timeFormat = "h时";
		} else if (mode === "日") {
			// 日
			let {
				todayStart
			} = vk.pubfn.getCommonTime();
			// 在今日的时间上往前推
			for (let i = -1; i < 28; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(todayStart, {
					day: i,
					mode: "before", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			timeFormat = "MM-dd";
		} else {
			// 月
			let {
				monthStart
			} = vk.pubfn.getCommonTime();
			// 在今日的时间上往前推12个月
			for (let i = -1; i < 12; i++) {
				let timeCalc = vk.pubfn.getOffsetTime(monthStart, {
					month: i,
					mode: "before", // after 之后 before 之前
				});
				boundaries.push(timeCalc);
			}
			timeFormat = "M月";
		}

		// 数组顺序反转（必须从小到大排序）
		boundaries.reverse();
		// 数据库查询
		let dbRes = await db
			.collection(dbName.order)
			.aggregate()
			.match({
				status: _.in([-3, -4]),
				refund_time: _.gte(boundaries[0]).lte(
					boundaries[boundaries.length - 1]
				),
			})
			.bucket({
				groupBy: "$refund_time",
				boundaries,
				default: "other",
				output: {
					count: $.sum(1),
				},
			})
			.end();

		// 组装数据返回
		res.list = boundaries.map((groupItem) => {
			let findItem = dbRes.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, timeFormat);
			let value = findItem && findItem.count ? findItem.count : 0;
			return {
				value,
				text,
				group,
			};
		});
		// 删除最后一个数据
		res.list.pop();

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 订单数量统计
	 * @url admin/business/kh.stats.getOrderCount 前端调用的url参数地址
	 */
	getOrderCount: async function(data) {
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		let {
			todayStart,
			yesterdayStart
		} = vk.pubfn.getCommonTime();
		let boundaries1 = [];
		let boundaries2 = [];
		//24小时
		for (let i = 0; i <= 24; i++) {
			let timeCalc1 = vk.pubfn.getOffsetTime(todayStart, {
				hour: i,
				mode: "after", // after 之后 before 之前
			});
			boundaries1.push(timeCalc1);
			let timeCalc2 = vk.pubfn.getOffsetTime(yesterdayStart, {
				hour: i,
				mode: "after", // after 之后 before 之前
			});
			boundaries2.push(timeCalc2);
		}
		// 数据库查询
		let dbRes1 = await db
			.collection(dbName.order)
			.aggregate()
			.match({
				status: _.gt(0),
				pay_time: _.gte(boundaries1[0]).lte(
					boundaries1[boundaries1.length - 1]
				),
			})
			.bucket({
				groupBy: "$pay_time",
				boundaries: boundaries1,
				default: "other",
				output: {
					sum: $.sum("$amount_info.payment_amount")
				},
			})
			.end();
		res.sumToday = 0;
		res.list1 = boundaries1.map((groupItem) => {
			let findItem = dbRes1.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, "hh");
			let value = findItem && findItem.sum ? findItem.sum / 100 : 0;
			res.sumToday += value * 100;
			return {
				value,
				text,
				group: "今日订单"
			};
		});
		res.list1[res.list1.length - 1].text = "24";

		let dbRes2 = await db
			.collection(dbName.order)
			.aggregate()
			.match({
				status: _.gt(0),
				pay_time: _.gte(boundaries2[0]).lte(
					boundaries2[boundaries2.length - 1]
				),
			})
			.bucket({
				groupBy: "$pay_time",
				boundaries: boundaries2,
				default: "other",
				output: {
					sum: $.sum("$amount_info.payment_amount")
				},
			})
			.end();
		res.list2 = boundaries2.map((groupItem) => {
			let findItem = dbRes2.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, "hh");
			let value = findItem && findItem.sum ? findItem.sum / 100 : 0;
			return {
				value,
				text,
				group: "昨日订单"
			};
		});
		res.list2[res.list2.length - 1].text = "24";
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 订单状态分组
	 * @url admin/business/kh.stats.getOrderStatusGroup 前端调用的url参数地址
	 */
	getOrderStatusGroup: async function(data) {
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		let {
			todayStart,
			yesterdayStart,
			todayEnd,
			yesterdayEnd,
			monthStart,
			monthEnd,
			lastMonthStart,
			lastMonthEnd,
		} = vk.pubfn.getCommonTime();
		let boundaries1 = [];
		//24小时
		for (let i = 0; i <= 24; i++) {
			let timeCalc1 = vk.pubfn.getOffsetTime(todayStart, {
				hour: i,
				mode: "after", // after 之后 before 之前
			});
			boundaries1.push(timeCalc1);
		}
		// 数据库查询
		let dbRes1 = await db
			.collection(dbName.order)
			.aggregate()
			.match({
				status: _.gt(0),
				pay_time: _.gte(boundaries1[0]).lte(
					boundaries1[boundaries1.length - 1]
				),
			})
			.bucket({
				groupBy: "$pay_time",
				boundaries: boundaries1,
				default: "other",
				output: {
					count: $.sum(1)
				},
			})
			.end();
		console.log(dbRes1);
		let list1 = boundaries1.map((groupItem) => {
			let findItem = dbRes1.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, "hh");
			let value = findItem && findItem.count ? findItem.count : 0;
			res.orderNum += value;
			return {
				value,
				text,
				group: "订单数"
			};
		});
		list1.pop();

		let dbRes2 = await db
			.collection(dbName.order)
			.aggregate()
			.match({
				pay_time: _.gte(boundaries1[0]).lte(
					boundaries1[boundaries1.length - 1]
				),
			})
			.group({
				_id: "$user_id", // _id是分组id（_id:为固定写法，必填属性），这里指按user_id字段进行分组
				count: _.$.sum(1), // count记录条数
				pay_time: _.$.first("$pay_time"), // pay_time记录条数
			})
			.bucket({
				groupBy: "$pay_time",
				boundaries: boundaries1,
				default: "other",
				output: {
					count: $.sum(1)
				},
			})
			.end();
		let list2 = boundaries1.map((groupItem) => {
			let findItem = dbRes2.data.find((item) => {
				return item._id === groupItem;
			});
			let text = vk.pubfn.timeFormat(groupItem, "hh");
			let value = findItem && findItem.count ? findItem.count : 0;
			res.orderUser += value;
			return {
				value,
				text,
				group: "支付人数"
			};
		});
		list2.pop();
		// 并发
		let batchRunRes = await vk.pubfn.batchRun({
			main: [
				// 今日订单数
				async () => {
						return await vk.baseDao.count({
							dbName: "vk-mall-order",
							whereJson: {
								pay_time: _.gte(todayStart).lte(todayEnd)
							},
						});
					},
					// 今日支付人数
					async () => {
							let dbRes2 = await db
								.collection(dbName.order)
								.aggregate()
								.match({
									pay_time: _.gte(todayStart).lte(todayEnd),
								})
								.group({
									_id: "$user_id", // _id是分组id（_id:为固定写法，必填属性），这里指按user_id字段进行分组
									count: _.$.sum(1), // count记录条数
									pay_time: _.$.first("$pay_time"), // pay_time记录条数
								})
								.bucket({
									groupBy: "$pay_time",
									boundaries: [todayStart, todayEnd],
									default: "other",
									output: {
										count: $.sum(1)
									},
								})
								.end();
							let todayPayUser = dbRes2.data.find((item) => {
								return item._id === todayStart;
							});
							return todayPayUser ? todayPayUser.count : 0;
						},
						// 昨日订单数
						async () => {
								return await vk.baseDao.count({
									dbName: "vk-mall-order",
									whereJson: {
										pay_time: _.gte(yesterdayStart).lte(yesterdayEnd)
									},
								});
							},
							// 昨日支付人数
							async () => {
									let dbRes2 = await db
										.collection(dbName.order)
										.aggregate()
										.match({
											pay_time: _.gte(yesterdayStart).lte(yesterdayEnd),
										})
										.group({
											_id: "$user_id", // _id是分组id（_id:为固定写法，必填属性），这里指按user_id字段进行分组
											count: _.$.sum(1), // count记录条数
											pay_time: _.$.first("$pay_time"), // pay_time记录条数
										})
										.bucket({
											groupBy: "$pay_time",
											boundaries: [yesterdayStart, yesterdayEnd],
											default: "other",
											output: {
												count: $.sum(1)
											},
										})
										.end();
									let yesterdayPayUser = dbRes2.data.find((item) => {
										return item._id === yesterdayStart;
									});
									return yesterdayPayUser ? yesterdayPayUser.count : 0;
								},
								// 本月订单数
								async () => {
										return await vk.baseDao.count({
											dbName: "vk-mall-order",
											whereJson: {
												pay_time: _.gte(monthStart).lte(monthEnd)
											},
										});
									},
									// 本月支付人数
									async () => {
											let dbRes2 = await db
												.collection(dbName.order)
												.aggregate()
												.match({
													pay_time: _.gte(monthStart).lte(monthEnd),
												})
												.group({
													_id: "$user_id", // _id是分组id（_id:为固定写法，必填属性），这里指按user_id字段进行分组
													count: _.$.sum(1), // count记录条数
													pay_time: _.$.first("$pay_time"), // pay_time记录条数
												})
												.bucket({
													groupBy: "$pay_time",
													boundaries: [monthStart, monthEnd],
													default: "other",
													output: {
														count: $.sum(1)
													},
												})
												.end();
											let monthPayUser = dbRes2.data.find((item) => {
												return item._id === monthStart;
											});
											return monthPayUser ? monthPayUser.count : 0;
										},
										// 上月订单数
										async () => {
												return await vk.baseDao.count({
													dbName: "vk-mall-order",
													whereJson: {
														pay_time: _.gte(lastMonthStart).lte(lastMonthEnd)
													},
												});
											},
											// 上月支付人数
											async () => {
												let dbRes2 = await db
													.collection(dbName.order)
													.aggregate()
													.match({
														pay_time: _.gte(lastMonthStart).lte(lastMonthEnd),
													})
													.group({
														_id: "$user_id", // _id是分组id（_id:为固定写法，必填属性），这里指按user_id字段进行分组
														count: _.$.sum(1), // count记录条数
														pay_time: _.$.first("$pay_time"), // pay_time记录条数
													})
													.bucket({
														groupBy: "$pay_time",
														boundaries: [lastMonthStart, lastMonthEnd],
														default: "other",
														output: {
															count: $.sum(1)
														},
													})
													.end();
												let lastMonthPayUser = dbRes2.data.find((item) => {
													return item._id === lastMonthStart;
												});
												return lastMonthPayUser ? lastMonthPayUser.count : 0;
											},
			],
			// 最大并发量，如果设置为1，则会按顺序执行
			concurrency: 10,
		});

		res.list = batchRunRes.stack;
		res.list1 = list1;
		res.list2 = list2;
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 商品数量统计
	 * @url admin/business/kh.stats.getGoodsCount 前端调用的url参数地址
	 */
	getGoodsCount: async function(data) {
		let res = {
			code: 0,
			msg: "",
		};
		// 业务逻辑开始-----------------------------------------------------------
		// 并发
		let batchRunRes = await vk.pubfn.batchRun({
			// 主执行函数
			main: [
				// 总数量
				async () => {
						return await vk.daoCenter.goodsDao.count({
							status: _.in([1, 2]),
						});
					},
					// 销售中
					async () => {
							return await vk.daoCenter.goodsDao.count({
								status: 1,
								is_on_sale: true,
							});
						},
						// 已缺货
						async () => {
								return await vk.daoCenter.goodsDao.count({
									status: 1,
									is_on_sale: true,
									stock: 0,
								});
							},
							// 回收站
							async () => {
								return await vk.daoCenter.goodsDao.count({
									status: 3,
								});
							},
			],
			// 最大并发量，如果设置为1，则会按顺序执行
			concurrency: 10,
		});
		res.list = batchRunRes.stack;
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 商品销量排行榜
	 * @url admin/business/kh.stats.getGoodsSellRank 前端调用的url参数地址
	 */
	getGoodsSellRank: async function(data) {
		let res = {
			code: 0,
			msg: "",
		};
		// 业务逻辑开始-----------------------------------------------------------
		let {
			mode = "count"
		} = data;
		let groupJson = {
			_id: "$goods_id",
		};
		let sortArr = [];
		let group = "";
		if (mode === "count") {
			groupJson["total"] = _.$.sum("$buy_num");
			group = "商品销量";
		} else {
			groupJson["total"] = _.$.sum("$amount.goods_payment_amount");
			group = "商品销售额";
		}
		let list = await vk.baseDao.selects({
			dbName: dbName.userGoodsPer,
			pageIndex: 1,
			pageSize: 10,
			getMain: true,
			// 主表where条件
			whereJson: {},
			groupJson,
			sortArr: [{
				name: "total",
				type: "desc",
			}, ],
			// 副表列表
			foreignDB: [{
				dbName: dbName.goods,
				localKey: "_id",
				foreignKey: "_id",
				as: "goodsInfo",
				limit: 1,
				fieldJson: {
					name: 1,
					goods_thumb: 1,
				},
			}, ],
			lastWhereJson: {
				goodsInfo: _.exists(true),
			},
		});
		// 组装数据返回
		res.list = list.map((groupItem) => {
			let text = groupItem.goodsInfo.name;
			let value = groupItem.total;
			if (mode === "amount") {
				value = vk.pubfn.toDecimal(value / 100, 2);
			}
			return {
				value,
				text,
				group,
			};
		});
		if (vk.pubfn.isNull(res.list)) {
			res.list = [{
				value: 0,
				text: "暂无数据",
				group,
			}, ];
		}
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 商品浏览量排行
	 * @url admin/business/kh.stats.getGoodsViewCount 前端调用的url参数地址
	 */
	getGoodsViewCount: async function(data) {
		let res = {
			code: 0,
			msg: "",
		};
		// 业务逻辑开始-----------------------------------------------------------
		let list = await vk.baseDao.select({
			dbName: dbName.goods,
			getCount: false,
			pageIndex: 1,
			pageSize: 20,
			getMain: true,
			whereJson: {
				status: 1,
			},
			sortArr: [{
				name: "view_count",
				type: "desc",
			}, ],
		});
		// 组装数据返回
		res.list = list.map((groupItem) => {
			let text = groupItem.name;
			let value = groupItem.view_count;
			let group = "商品浏览量";
			return {
				value,
				text,
				group,
			};
		});
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 模板函数
	 * @url admin/business/kh.stats.test 前端调用的url参数地址
	 */
	test: async function(data) {
		let res = {
			code: 0,
			msg: "",
		};
		// 业务逻辑开始-----------------------------------------------------------

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
};

module.exports = cloudObject;
